package com.andromouse;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPServer implements Runnable {
	BufferedReader in;
	PrintWriter out;
	FileBrowserServer fbs = null;
	private int port;
	boolean isPassword;

	public void run() {
		this.port = Utils.port;
		this.isPassword = Utils.isPassword;
		try {
			ServerSocket s = new ServerSocket(this.port);
			while (true) {
				Socket incoming = s.accept();
				s.setSoTimeout(2500);
				this.in = new BufferedReader(new InputStreamReader(
						incoming.getInputStream()));
				this.out = new PrintWriter(new OutputStreamWriter(
						incoming.getOutputStream()));
				write("AMServer");

				this.out.flush();
				while (true) {
					String str = read();

					if (str == null) {
						break;
					}
					Utils.status = 1;
					this.out.println("AMServer: " + str);
					this.out.flush();
				}

				incoming.close();
			}
		} catch (Exception e) {
			Utils.status = 0;
		}
	}

	public String read() {
		String msg = null;
		try {
			msg = this.in.readLine();
			handleSystemMessages(msg);
		} catch (IOException localIOException) {
		}
		return msg;
	}

	public void write(String msg) {
		this.out.println(msg);
	}

	public void handleSystemMessages(String message) {
		if ((message.contains("AMPASSCHECK")) && (this.isPassword)) {
			String password = Utils.password;
			write("AMServPass:" + password);
		}
	}
}
